package main

import (
	"github.com/kataras/iris"
	"github.com/kataras/iris/middleware/logger"
	"huolitiyu/config"
	"huolitiyu/database"
	_ "huolitiyu/database"
	"huolitiyu/models"
)

var (
	app *iris.Application
)

func newApp() (app *iris.Application) {
	app = iris.New()
	app.Use(logger.New())

	iris.RegisterOnInterrupt(func() {
		database.DB.Close()
	})

	// 自动迁移数据表，根据模型定义生成/更新数据表定义
	database.DB.
		Set("gorm:table_options", "ENGINE=InnoDB").
		AutoMigrate(&models.User{})

	app.OnErrorCode(iris.StatusNotFound, func(ctx iris.Context) {
		ctx.HTML("404 Not Found")
	})

	app.OnErrorCode(iris.StatusInternalServerError, func(ctx iris.Context) {
		ctx.HTML("500 Server Error");
	})

	return app
}

func main() {
	app = newApp()
	addr := config.Conf.Get("app.addr").(string)

	// 注册静态资源访问
	app.StaticWeb("/public", "public")

	// 注册iris渲染视图
	viewEngine := iris.HTML("views", ".html")
	viewEngine.Reload(true)
	viewEngine.Layout("shared/layout.html")
	app.RegisterView(viewEngine)

	app.Get("/", func(ctx iris.Context) {
		ctx.ViewData("Title", "首页")
		ctx.ViewData("HomeData", "首页内容")
		user := models.User{}
		database.DB.First(&user)
		ctx.ViewData("User", user)
		ctx.View("test/index.html")
	})

	app.Run(
		iris.Addr(addr),
		iris.WithCharset("UTF-8"),
	)
}